//------------------------------------------------------------------------------
// <copyright file="ItemsCollectionControl.xaml.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using DotBeer.Business.Entities;
using DotBeer.Data.Properties;
using DAnton.Utilities.Extensions;
using DotBeer.Business.Components;
using DAnton.Utilities.Helpers;
using System.Collections.Specialized;
using DotBeer.Business.Components.Exceptions;

namespace DotBeer.UI.WPFClient
{
    /// <summary>
    /// Interaction logic for WindowItemsCollection.xaml
    /// </summary>
    public partial class ItemsCollectionControl : UserControl, IOptionsControl
    {
        #region private members

        List<string> filesToDelete = new List<string>();
        ItemsCollection itemsCollection;
        IList<Item> itemsCopy;
        bool changesSaved = true;

        #endregion

        #region constructors

        public ItemsCollectionControl()
        {
            InitializeComponent();

            ItemsCollectionControlSettings.Default.SettingsSaving += new SettingsSavingEventHandler(this.ItemsCollectionControlSettings_SettingsSaving);

            try
            {
                this.itemsCollection = ItemsCollectionComponent.Load();
                this.itemsCollection.Items.CollectionChanged += new NotifyCollectionChangedEventHandler(this.Items_CollectionChanged);

                foreach (Item item in this.itemsCollection.Items)
                    item.PropertyChanged += new PropertyChangedEventHandler(this.item_PropertyChanged);

                this.DataContext = this.itemsCollection;
                this.itemsCopy = this.itemsCollection.Items.Clone();
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show(String.Format("Error occured while loading items collection: \n{0}", ex.Message), "Error");
            }
        }

        #endregion

        #region public methods

        #region IOptionsControl Members

        public bool Save()
        {
            bool result = true;

            foreach (string filePath in this.filesToDelete)
            {
                try
                {
                    File.Delete(filePath);
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show(String.Format("Error occured while deleting file: \n{0}", ex.Message), "Error");
                    result = false;
                }
            }

            try
            {
                ItemsCollectionComponent.Save(this.itemsCollection);
                this.changesSaved = true;
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show(String.Format("Error occured while saving items collection: \n{0}", ex.Message), "Error");
                result = false;
            }

            return result;
        }

        public void Cancel()
        {
            if (!this.changesSaved)
            {
                this.itemsCollection.Items.Clear();
                this.itemsCollection.Items.AddRange(this.itemsCopy);
            }
        }

        #endregion

        #endregion

        #region private methods

        #region user action's

        private void ButtonAddNewItem_Click(object sender, RoutedEventArgs e)
        {
            WindowAddNewObject winNew = new WindowAddNewObject("item");

            if (winNew.ShowDialog() == true)
            {
                string newItemName = winNew.NewObjectName.Trim();

                if (this.itemsCollection.Items.SingleOrDefault(item => item.Name.ToUpper() == newItemName.ToUpper()) == null)
                {
                    Item newItem = new Item()
                    {
                        Name = winNew.NewObjectName,
                        ItemsCollection = this.itemsCollection
                    };

                    this.itemsCollection.Items.Add(newItem);
                    this.itemsCollection.Items.Sort(i => i.Name, ListSortDirection.Ascending);

                    this.listViewItems.ScrollIntoView(newItem);
                    this.listViewItems.SelectedItem = newItem;
                }
                else
                    CustomMessageBox.Show(String.Format("Item: \"{0}\" is already on the list.", newItemName),
                                        "Error");
            }
        }

        private void listViewItems_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete && this.listViewItems.SelectedItem != null)
            {
                Item item = (Item)this.listViewItems.SelectedItem;
                ((ObservableCollection<Item>)this.listViewItems.ItemsSource).Remove(item);

                filesToDelete.Add(item.ImagePath);
            }
        }

        private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = !NumericValidation.IsNumeric(e.Text);
        }

        private void ButtonImagePath_Click(object sender, RoutedEventArgs e)
        {
            string fileName = Dialogs.OpenImageFileDialog();

            if (fileName != null && this.listViewItems.SelectedItem != null)
            {
                Item hero = (Item)this.listViewItems.SelectedItem;

                try
                {
                    hero.ImagePath = fileName;
                }
                catch (Exception ex)
                {
                    HandleExceptions.UIPolicy(ex);
                }
            }
        }

        #endregion

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.CheckboxDownloadImage.IsChecked = ItemsCollectionControlSettings.Default.DownloadItemImage;

            this.listViewItems.SelectionChanged += new SelectionChangedEventHandler(listViewItems_SelectionChanged);
            this.listViewItems_SelectionChanged(this, null);
        }

        private void AddImageDownloaderControl()
        {
            if (ItemsCollectionControlSettings.Default.DownloadItemImage)
            {
                ImageDownloaderControl imgDown = new ImageDownloaderControl();
                imgDown.Name = "ImageDownloader";
                imgDown.SetValue(Grid.RowProperty, 3);
                imgDown.SetValue(Grid.ColumnProperty, 7);

                Binding binding = new Binding();
                binding.Path = new PropertyPath("/Url");
                binding.Mode = BindingMode.OneWay;

                imgDown.SetBinding(ImageDownloaderControl.ImageUrlProperty, binding);
                this.GridInputControls.Children.Add(imgDown);

                this.TextBoxUrl.SetValue(Grid.ColumnSpanProperty, 6);
            }
            else
            {
                this.TextBoxUrl.SetValue(Grid.ColumnSpanProperty, 7);
            }
        }

        private void RemoveImageDownloaderControl()
        {
            UserControl cont = UIHelper.FindVisualChildByName<UserControl>(this.GridInputControls, "ImageDownloader");

            if (cont != null)
            {
                this.GridInputControls.Children.Remove(cont);
                this.TextBoxUrl.SetValue(Grid.ColumnSpanProperty, 7);
            }
        }

        private void CheckboxDownloadImage_Checked(object sender, RoutedEventArgs e)
        {
            ItemsCollectionControlSettings.Default.DownloadItemImage = true;
            ItemsCollectionControlSettings.Default.Save();
            AddImageDownloaderControl();
        }

        private void CheckboxDownloadImage_Unchecked(object sender, RoutedEventArgs e)
        {
            ItemsCollectionControlSettings.Default.DownloadItemImage = false;
            ItemsCollectionControlSettings.Default.Save();
            RemoveImageDownloaderControl();
        }

        private void listViewItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.listViewItems.SelectedItem != null)
            {
                ObjectDataProvider itemsListProvider = (ObjectDataProvider)this.FindResource("ItemsListDS");
                ItemsList itemsList = (ItemsList)itemsListProvider.Data;
                itemsList.ExcludeItemFromList((Item)this.listViewItems.SelectedItem);
            }
        }

        private void ItemsCollectionControlSettings_SettingsSaving(object sender, CancelEventArgs e)
        {
            this.AddImageDownloaderControl();
        }

        private void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.changesSaved = false;
        }

        private void Items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                this.changesSaved = false;
                ((Item)e.OldItems[0]).PropertyChanged -= this.item_PropertyChanged;
            }
            else if (e.Action == NotifyCollectionChangedAction.Add)
            {
                this.changesSaved = false;
                this.itemsCollection.Items[e.NewStartingIndex].PropertyChanged += new PropertyChangedEventHandler(this.item_PropertyChanged);
            }
        }

        #endregion
    }
}
